
host = 'tenant-2102622389-cn-guangzhou-public.bytehouse.volces.com'
port = 3306
database = 'strategy_cloud'
username = 'bytehouse'
password = 'gd3gjGTXTb:WBSEjA67dI'

def main(database: str, host: str, port: str, username: str, password: str) -> dict:
    import pymysql
    import datetime
    from decimal import Decimal
    from collections import defaultdict

    # 创建数据库连接
    connection = pymysql.connect(
        host=host,
        port=int(port),
        user=username,
def main(database: str, host: str, port: str, username: str, password: str) -> dict:
    import pymysql
    import datetime
    from decimal import Decimal
    from collections import defaultdict

    # 创建数据库连接
    connection = pymysql.connect(
        host=host,
        port=int(port),
        user=username,
        password=password,
        database=database,
        charset='utf8mb4'
    )
    cursor = connection.cursor()

    # 获取所有表名

    cursor.execute(
        'SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s',
        (database,)
    )
    tables = [row[0] for row in cursor.fetchall()]
    result = []

    for table in tables:
        try:
            # 获取DDL
            cursor.execute(f'SHOW CREATE TABLE `{table}`')
            create_table_row = cursor.fetchone()
            ddl = create_table_row[1] if create_table_row else ''

            # 获取前5行数据
            cursor.execute(f'SELECT * FROM `{table}` LIMIT 2')
            data_rows = cursor.fetchall()
            columns = [col[0] for col in cursor.description]

            # 获取字段类型信息
            cursor.execute(f'''
                SELECT COLUMN_NAME, DATA_TYPE 
                FROM information_schema.COLUMNS 
                WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
            ''', (database, table))
            column_types = {col_name: data_type.lower() for col_name, data_type in cursor.fetchall()}
            
            # # 收集字符串字段的枚举值
            # string_columns = [col for col in columns if column_types.get(col, '').startswith(('char', 'varchar', 'text', 'enum'))]
            # enum_values = {}
            
            # if string_columns:
            #     for col in string_columns:
            #         # 检查该列的不同值数量
            #         cursor.execute(f'''
            #             SELECT COUNT(DISTINCT `{col}`) 
            #             FROM `{table}`
            #         ''')
            #         distinct_count = cursor.fetchone()[0]
                    
            #         # 如果不同值数量超过500，则跳过
            #         if distinct_count is not None and distinct_count > 100:
            #             # enum_values[col] = f"超过500个不同值 ({distinct_count})"
            #             continue
                    
            #         # 获取所有不同的值
            #         cursor.execute(f'''
            #             SELECT DISTINCT `{col}` 
            #             FROM `{table}` 
            #             WHERE `{col}` IS NOT NULL
            #         ''')
            #         values = [row[0] for row in cursor.fetchall()]
                    
            #         # 处理值的类型确保JSON可序列化
            #         processed_values = []
            #         for value in values:
            #             if isinstance(value, (datetime.date, datetime.datetime)):
            #                 processed_values.append(value.isoformat())
            #             elif isinstance(value, Decimal):
            #                 processed_values.append(float(value))
            #             elif isinstance(value, (bytes, bytearray)):
            #                 processed_values.append(value.decode('utf-8', 'replace'))
            #             else:
            #                 processed_values.append(value)
                    
            #         enum_values[col] = processed_values

            # 处理数据类型确保JSON可序列化
            data = []
            for row in data_rows:
                processed_row = {}
                for idx, value in enumerate(row):
                    col_name = columns[idx]
                    # 处理常见不可序列化类型
                    if isinstance(value, (datetime.date, datetime.datetime)):
                        processed_row[col_name] = value.isoformat()
                    elif isinstance(value, Decimal):
                        processed_row[col_name] = float(value)
                    elif isinstance(value, (bytes, bytearray)):
                        processed_row[col_name] = value.decode('utf-8', 'replace')
                    else:
                        processed_row[col_name] = value
                data.append(processed_row)
            result.append({
                "table": table,
                "ddl": ddl,
                "data": data,
                # "enum_values": enum_values
            })
        except Exception as e:
            print(f"处理表 {table} 时出错: {str(e)}")
            continue

    cursor.close()
    connection.close()
    return {"result": str(result)}
        password=password,
        database=database,
        charset='utf8mb4'
    )
    cursor = connection.cursor()

    # 获取所有表名

    cursor.execute(
        'SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s',
        (database,)
    )
    tables = [row[0] for row in cursor.fetchall()]
    result = []

    for table in tables:
        try:
            # 获取DDL
            cursor.execute(f'SHOW CREATE TABLE `{table}`')
            create_table_row = cursor.fetchone()
            ddl = create_table_row[1] if create_table_row else ''

            # 获取前5行数据
            cursor.execute(f'SELECT * FROM `{table}` LIMIT 2')
            # data_rows = cursor.fetchall()
            columns = [col[0] for col in cursor.description]
            conditions = [f"{col} IS NOT NULL" for col in columns]
            cursor.execute(f'''
            SELECT *
            WHERE {" AND ".join(conditions)}
            LIMIT 10;
            ''')

            # 获取字段类型信息
            cursor.execute(f'''
                SELECT COLUMN_NAME, DATA_TYPE 
                FROM information_schema.COLUMNS 
                WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
            ''', (database, table))
            column_types = {col_name: data_type.lower() for col_name, data_type in cursor.fetchall()}
            
            # # 收集字符串字段的枚举值
            # string_columns = [col for col in columns if column_types.get(col, '').startswith(('char', 'varchar', 'text', 'enum'))]
            # enum_values = {}
            
            # if string_columns:
            #     for col in string_columns:
            #         # 检查该列的不同值数量
            #         cursor.execute(f'''
            #             SELECT COUNT(DISTINCT `{col}`) 
            #             FROM `{table}`
            #         ''')
            #         distinct_count = cursor.fetchone()[0]
                    
            #         # 如果不同值数量超过500，则跳过
            #         if distinct_count is not None and distinct_count > 100:
            #             # enum_values[col] = f"超过500个不同值 ({distinct_count})"
            #             continue
                    
            #         # 获取所有不同的值
            #         cursor.execute(f'''
            #             SELECT DISTINCT `{col}` 
            #             FROM `{table}` 
            #             WHERE `{col}` IS NOT NULL
            #         ''')
            #         values = [row[0] for row in cursor.fetchall()]
                    
            #         # 处理值的类型确保JSON可序列化
            #         processed_values = []
            #         for value in values:
            #             if isinstance(value, (datetime.date, datetime.datetime)):
            #                 processed_values.append(value.isoformat())
            #             elif isinstance(value, Decimal):
            #                 processed_values.append(float(value))
            #             elif isinstance(value, (bytes, bytearray)):
            #                 processed_values.append(value.decode('utf-8', 'replace'))
            #             else:
            #                 processed_values.append(value)
                    
            #         enum_values[col] = processed_values

            # 处理数据类型确保JSON可序列化
            data = []
            for row in data_rows:
                processed_row = {}
                for idx, value in enumerate(row):
                    col_name = columns[idx]
                    # 处理常见不可序列化类型
                    if isinstance(value, (datetime.date, datetime.datetime)):
                        processed_row[col_name] = value.isoformat()
                    elif isinstance(value, Decimal):
                        processed_row[col_name] = float(value)
                    elif isinstance(value, (bytes, bytearray)):
                        processed_row[col_name] = value.decode('utf-8', 'replace')
                    else:
                        processed_row[col_name] = value
                data.append(processed_row)
            result.append({
                "table": table,
                "ddl": ddl,
                "data": data,
                # "enum_values": enum_values
            })
        except Exception as e:
            print(f"处理表 {table} 时出错: {str(e)}")
            continue

    cursor.close()
    connection.close()
    return {"result": str(result)}